package com.example.datachangerecord.record;


import com.example.datachangerecord.record.eneity.ContextRecordData;
import com.example.datachangerecord.record.processor.RequestRecordProcessor;
import jakarta.servlet.http.HttpServletRequest;
import lombok.SneakyThrows;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.List;


/**
 * @author xyj
 */
@Aspect
@Component
public class RecordAspect {

    @Autowired
    private RequestRecordProcessor processor;


    @Pointcut("@annotation(com.example.datachangerecord.record.annotation.Record)")
    public void reCord() {

    }

    @Pointcut("@annotation(com.example.datachangerecord.record.annotation.Records)")
    public void reCords() {

    }

    /**
     * 信息记录环绕处理
     */

    @SneakyThrows
    @Around("reCord()")
    public Object doAround(ProceedingJoinPoint jp) {
        List<? extends ContextRecordData> contextRecordData = null;
        try {
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            HttpServletRequest request = attributes.getRequest();
            contextRecordData = processor.beforeProceed(jp, request);
        } catch (Exception ignored) {

        }

        Object result = jp.proceed();


        try {
            processor.afterProceed(contextRecordData);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }


        return result;
    }
}
